package com.aiyige.utils.removal;

import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.util.Log;

import com.aiyige.base.db.dao.DownloadFileDao;
import com.aiyige.base.db.dao.DownloadModelDao;
import com.aiyige.base.db.table.DownloadFile;
import com.aiyige.base.db.table.DownloadModel;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.UUIDUtil;
import com.aiyige.utils.VideoUtil;
import com.aiyige.utils.removal.dao.CacheTaskDao;
import com.aiyige.utils.removal.dao.ReLocalMovieDao;
import com.aiyige.utils.removal.dao.VideoCacheDao;
import com.aiyige.utils.removal.entity.CacheTaskEntity;
import com.aiyige.utils.removal.entity.ReLocalMovieInfo;
import com.aiyige.utils.removal.entity.VideoCacheEntity;
import com.aiyige.utils.removal.model.VideoCacheChildModel;
import com.aiyige.utils.removal.model.VideoCacheParentModel;
import com.vondear.rxtools.RxFileTool;

import java.util.ArrayList;
import java.util.List;

/**
 * 中舞网数据迁移工具
 */
public class RemovalHandler {
    private static final String TAG = "RemovalHandler";
    private List<VideoCacheEntity> videoCourseList;// 教学视频列表

    private List<VideoCacheEntity> videoList; // 普通视频列表

    private List<VideoCacheEntity> localVideoList; // 本地视频列表


    static RemovalHandler instance;

    private static VideoCacheDao cacheDao;

    private static CacheTaskDao taskDao;

    private static ReLocalMovieDao localDao;

    RemovalCallback callback;

    public static boolean isDebug = true; // debug模式下 忽略用户id直接把数据查询出来

    public RemovalCallback getCallback() {
        return callback;
    }

    public void setCallback(RemovalCallback callback) {
        this.callback = callback;
    }

    public static RemovalHandler getInstance() {
        if (instance == null) {
            instance = new RemovalHandler();
        }
        if (cacheDao == null) {
            cacheDao = new VideoCacheDao();
        }
        if (taskDao == null) {
            taskDao = new CacheTaskDao();
        }
        if (localDao == null) {
            localDao = new ReLocalMovieDao();
        }

        return instance;
    }

    /**
     * 返回缓存数据集（已完成或未完成都包含）
     * VideoCacheParentModel
     *
     * @return
     */
    public synchronized void getAllList(final RemovalCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 根据userId查询缓存task
                    List<CacheTaskEntity> taskList = taskDao.queryAllCachesByUserId();
                    if (ListUtil.isEmpty(taskList)) {
                        return;
                    }
                    int taskSize = taskList.size();
                    Log.i(TAG, "taskList size is " + taskSize);
                    List<VideoCacheParentModel> list = new ArrayList<>();
                    for (CacheTaskEntity task : taskList) {
                        // 根据task的serverCode 查询子视频列表
                        if (!TextUtils.isEmpty(task.getServerCode())) {
                            List<VideoCacheEntity> videoCacheList = cacheDao.queryCacheVideoByServerCode(task.getServerCode());
                            if (ListUtil.isEmpty(videoCacheList)) {
                                continue;
                            } else {
                                VideoCacheParentModel model = getVideoCacheParentModel(task, videoCacheList);
                                if (model != null) {
                                    list.add(model);
                                }
                            }
                        }
                    }
                    if (callback != null) {
                        callback.success(list);
                    }
                } catch (Exception e) {

                }
            }
        }).start();

    }


    /**
     * 开始中舞网缓存数据迁移(登录)
     */
    public void doRemoval() {
        getAllList(new RemovalCallback() {
            @Override
            public void success(List<VideoCacheParentModel> resultList) {
                if (ListUtil.isEmpty(resultList)) {
                    return;
                }
                DownloadUtil.removalDownloadVideo(resultList);
            }
        });

//        doRemovalLocalData();
    }

    /**
     * 开始中舞网缓存数据迁移
     */
    public void doRemovalLocalData() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                if (localDao != null) {
                    List<ReLocalMovieInfo> localList = localDao.queryLocalMovies();
                    if (!ListUtil.isEmpty(localList)) {

                        for (ReLocalMovieInfo localMedia : localList) {
                            try {
                                String coverLocalUrl = VideoUtil.getVideoCover(localMedia.getPath(), 0);
                                DownloadModel downloadModel = DownloadModel.newBuilder()
                                        .downloadDate(System.currentTimeMillis())
                                        .modelType(DownloadUtil.MODEL_TYPE_LOCAL_VIDEO)
                                        .controlOption(DownloadUtil.CONTROL_OPTION_DOWNLOAD)
                                        .coverLocalUrl(coverLocalUrl)
                                        .edit(false)
                                        .id(UUIDUtil.generate())
                                        .mediaNum(1)
                                        .userId(AccountUtil.getCurrentUser().getId())
                                        .progressStatus(DownloadUtil.PROGRESS_STATUS_DOWNLOAD_FINISHED)
                                        .title(FileUtil.getFileName(localMedia.getPath()))
                                        .releaseDate(System.currentTimeMillis())
                                        .build();
                                DownloadFile downloadFile = DownloadFile.newBuilder()
                                        .fileLocalUrl(localMedia.getPath())
                                        .fileType(DownloadUtil.DOWNLOAD_FILE_TYPE_VIDEO)
                                        .controlOption(DownloadUtil.CONTROL_OPTION_DOWNLOAD)
                                        .duration(localMedia.getDuration())
                                        .parentId(downloadModel.getId())
                                        .progressStatus(DownloadUtil.PROGRESS_STATUS_DOWNLOAD_FINISHED)
                                        .userId(AccountUtil.getCurrentUser().getId())
                                        .totalSize(FileUtil.getFileSize(localMedia.getPath()))
                                        .downloadedSize(FileUtil.getFileSize(localMedia.getPath()))
                                        .coverLocalUrl(coverLocalUrl)
                                        .title(FileUtil.getFileName(localMedia.getPath()))
                                        .build();
                                DownloadModelDao.getDao().create(downloadModel);
                                DownloadFileDao.getDao().create(downloadFile);
                            } catch (Exception e) {

                            }
                        }
                        localDao.clearTable();
                    }
                }
            }

            }).start();
        }

        private String getFileName (String fileName){
            String name = "";
            if (TextUtils.isEmpty(fileName)) {
                return "";
            }
            if (fileName.contains(".")) {
                String names[] = fileName.split("\\.");
                if (names != null && names.length > 0) {
                    name = names[0];
                }
            }
            return name;

        }


        /**
         * 视频列表筛选分类
         *
         * @param list
         * @param type 根据类型筛选列表，0表示普通视频  1表示教学视频
         *             <li>VideoCacheParentModel.TYPE_VIDEO</>
         *             <li>VideoCacheParentModel.TYPE_COURSE_VIDEO</>
         * @return
         */
        public List<VideoCacheParentModel> getVideoTypeList (List < VideoCacheParentModel > list,
        int type){
            if (ListUtil.isEmpty(list)) {
                return null;
            }
            List<VideoCacheParentModel> newList = new ArrayList<>();
            for (VideoCacheParentModel model : list) {
                if (model.getTypeId() == type) {
                    newList.add(model);
                }
            }
            return ListUtil.isEmpty(newList) ? null : newList;
        }


        /**
         * 把数据库类型转化为对外输出类型
         *
         * @param task
         * @param cacheList
         * @return
         */
        private VideoCacheParentModel getVideoCacheParentModel (CacheTaskEntity
        task, List < VideoCacheEntity > cacheList){
            if (task == null || ListUtil.isEmpty(cacheList)) {
                return null;
            }
            cacheList = cacheListDeleteDuplicate(cacheList);// 由于老代码没有判断重复数据问题，所以这里加一个去重逻辑
            List<VideoCacheChildModel> childList = new ArrayList<>();
            VideoCacheChildModel childModel;
            for (VideoCacheEntity cacheEntity : cacheList) {
                // 由于老中舞网App视频时长有bug，所以这里取平均值作为迁移的单集视频时长
                long duration = (cacheEntity.getDuration() * 1000) / cacheList.size();
                boolean fileExists = RxFileTool.isFileExists(cacheEntity.getPath());
                if (fileExists) {
                    MediaMetadataRetriever metadata = new MediaMetadataRetriever();
                    try {
                        metadata.setDataSource(cacheEntity.getPath());
                        String durationString = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                        duration = Long.parseLong(durationString);
                        metadata.release();
                    } catch (Exception e) {
                    }
                }

                childModel = VideoCacheChildModel.newBuilder()
                        .compeleteSize(cacheEntity.getCompeleteSize())
                        .duration(duration)
                        .imageUrl(cacheEntity.getImageUrl())
                        .isRead(cacheEntity.getIsRead())
                        .localId(cacheEntity.getLocalId())
                        .page(cacheEntity.getPage())
                        .path(cacheEntity.getPath())
                        .size(cacheEntity.getSize())
                        .title(cacheEntity.getTitle())
                        .url(cacheEntity.getUrl())
                        .videoId(cacheEntity.getVideoId())
                        .status(cacheEntity.getStatus()).build();
                childList.add(childModel);
            }

            if (!ListUtil.isEmpty(childList)) {
                VideoCacheParentModel parentModel = VideoCacheParentModel.newBuilder()
                        .childModelList(childList)
                        .completeSize(task.getCompleteSize())
                        .cover(task.getCover())
                        .createTime(task.getCreateTime())
                        .description(task.getDescription())
                        .downloadCount(task.getDownloadCount())
                        .localId(task.getLocalId())
                        .serverCode(task.getServerCode())
                        .size(task.getSize())
                        .status(task.getStatus())
                        .title(task.getTitle())
                        .typeId(task.getTypeId())
                        .userId(task.getUserId())
                        .videoId(task.getVideoId())
                        .total(task.getTotal())
                        .build();
                return parentModel;
            } else {
                return null;
            }

        }


        private List<VideoCacheEntity> cacheListDeleteDuplicate (List < VideoCacheEntity > list) {
            if (ListUtil.isEmpty(list)) {
                return null;
            }
            for (int i = 0; i < list.size() - 1; i++) {
                for (int j = list.size() - 1; j > i; j--) {
                    if (TextUtils.isEmpty(list.get(j).getPath()) || TextUtils.isEmpty(list.get(i).getPath())) {
                        continue;
                    }
                    if (list.get(j).getPath().equals(list.get(i).getPath())) {
                        list.remove(j);
                    }
                }
            }
            return list;
        }

        public interface RemovalCallback {
            void success(List<VideoCacheParentModel> resultList);
        }


        /**
         * 迁移完毕后删除原有的数据
         *
         * @param serverCodeList VideoCacheParentModel.serverCode
         * @return 返回执行成功的总数
         */
        public int deleteByUserId (List < String > serverCodeList) {
            if (ListUtil.isEmpty(serverCodeList)) {
                return 0;
            }
            int taskSuccessCount = taskDao.deleteServerCodeByUserId(serverCodeList);
            int cacheSuccessCount = cacheDao.deleteServerCodeByUserId(serverCodeList);
            return taskSuccessCount;
        }


        /**
         * debug模式下，忽略用户id，直接查询已有的缓存列表
         *
         * @param isDebug
         */
        public static void setDebug ( boolean isDebug){
            RemovalHandler.isDebug = isDebug;
        }


    }
